import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'package:path/path.dart';
import 'package:sweet_app/model/friend_model.dart';
import 'package:sweet_app/model/history_list_model.dart';
import 'package:sweet_app/model/message_model.dart';

class DatabaseHelper {
  static final DatabaseHelper _instance = DatabaseHelper.internal();

  factory DatabaseHelper() => _instance;

  static Database _db;

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await _initDb();
    return _db;
  }

  DatabaseHelper.internal();

  _initDb() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, "sweet_im_db.db");
    var ourDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return ourDb;
  }

  void _onCreate(Database db, int version) async {
    await db.execute(MESSAGE_TABLE_SQL);
    await db.execute(FRIEND_TABLE_SQL);
    await db.execute(HISTORY_LIST_TABLE_SQL);
    print("Table is created");
  }

  Future close() async {
    var dbClient = await db;
    return dbClient.close();
  }

  Future<int> insert(String sql, [List arguments]) async {
    var dbClient = await db;
    return dbClient.rawInsert(sql, arguments);
  }

  Future<int> update(String sql, [List arguments]) async {
    var dbClient = await db;
    return dbClient.rawUpdate(sql, arguments);
  }

  Future<int> delete(String sql, [List arguments]) async {
    var dbClient = await db;
    return dbClient.rawDelete(sql, arguments);
  }

  Future<List<Map<String,dynamic>>> query(String sql, [List arguments]) async {
    var db0 = await db;
    var data = await db0.rawQuery(sql, arguments);
    return data;
  }
}
